package com.phpxiu.app.view;

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.drawable.AnimationDrawable;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.KeyEvent;
import android.view.View;
import android.webkit.WebResourceError;
import android.webkit.WebResourceRequest;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Toast;

import com.phpxiu.app.kkylive.R;
import com.phpxiu.app.okhttp.OKHttp;
import com.phpxiu.app.okhttp.OKHttpCallback;

/**
 * @files
 * @brief Intagram授权界面
 * @author 吴金洲
 * @note Intagram授权界面：用户授权成功后拉取用户信息
 *
 */
public class InstOauthWeb extends UIBase {
    public final static String  USER_INFO="inst_user_info_json";
    private final static String CLIENT_ID="2994dcc60d7c4716a49dee20f18e1bec";
    private final static String REDIRECT_URL="http://www.kukuyu.cn/";
    private final static String SCOPE="basic";
    private final static String BASE_INST_OAUTH_URL = "https://api.instagram.com/oauth/authorize/";
    private final static String GET_SELF_URL="https://api.instagram.com/v1/users/self/?access_token=";
    private final static String INST_OATH_URL=BASE_INST_OAUTH_URL
            +"?client_id="
            +CLIENT_ID
            +"&redirect_uri="
            +REDIRECT_URL
            +"&response_type=token&display=touch&scope="//如果授权成功，返回token，否则返回错误信息
            +SCOPE;
    private WebView webView;
    private View coverView;
    private AnimationDrawable aniDraw;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.inst_oauth_web);
        coverView=findViewById(R.id.cover_view);
        aniDraw=(AnimationDrawable)findViewById(R.id.loadingImageView).getBackground();
        aniDraw.start();
        webView=(WebView)findViewById(R.id.inst_oauth_web_view);
        webView.setWebViewClient(new MWebViewClient());
        webView.getSettings().setSupportZoom(true);
        // 设置出现缩放工具
        webView.getSettings().setBuiltInZoomControls(false);
        webView.getSettings().setJavaScriptEnabled(true);
        //扩大比例的缩放
        webView.getSettings().setUseWideViewPort(true);
        webView.getSettings().setLayoutAlgorithm(WebSettings.LayoutAlgorithm.SINGLE_COLUMN);
        webView.getSettings().setLoadWithOverviewMode(true);
        webView.loadUrl(INST_OATH_URL);
    }

    /**
     * 设置回退
     * 覆盖Activity类的onKeyDown(int keyCoder,KeyEvent event)方法
     * @param keyCode
     * @param event
     * @return
     */
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if ((keyCode == KeyEvent.KEYCODE_BACK) && webView.canGoBack()) {
            webView.goBack(); // goBack()表示返回WebView的上一页面
            return true;
        }
        return super.onKeyDown(keyCode,event);
    }

    class MWebViewClient extends WebViewClient {
        @Override
        public void onPageStarted(WebView view, String url, Bitmap favicon) {
            super.onPageStarted(view, url, favicon);
            webView.setBackgroundColor(getResources().getColor(R.color.translucent));
        }

        @Override
        public void onPageFinished(WebView view, String url) {
            super.onPageFinished(view, url);
            webView.setBackgroundColor(getResources().getColor(R.color.translucent));
            coverView.setVisibility(View.INVISIBLE);
            webView.setVisibility(View.VISIBLE);
        }

        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            if(isFinishing()){
                return true;
            }
            if (url.toLowerCase().startsWith(REDIRECT_URL)) {
                if(url.indexOf("error")!=-1){//请求接口错误
                    String params=url.replace(REDIRECT_URL+"?","");
                    String reason=params.replace("&","\\n");
                    Toast.makeText(InstOauthWeb.this,reason,Toast.LENGTH_LONG).show();
                    return true;
                }
                final String token=url.replace(REDIRECT_URL+"#access_token=","");
                coverView.setVisibility(View.VISIBLE);
                OKHttp.get(GET_SELF_URL + token, "TAG", new OKHttpCallback(false) {
                    @Override
                    public void onSuccess(String result) {
                        Intent r = new Intent();
                        r.putExtra(USER_INFO, result);
                        setResult(RESULT_OK, r);
                        finish();
                    }

                    @Override
                    public void onErr(String msg) {
                        coverView.setVisibility(View.INVISIBLE);
                    }
                });
                return true;
            }
            webView.setBackgroundColor(getResources().getColor(R.color.translucent));
            return super.shouldOverrideUrlLoading(view, url);

        }

        @Override
        public void onReceivedError(WebView view, WebResourceRequest request, WebResourceError error) {
            super.onReceivedError(view, request, error);
            Intent intent = new Intent();
            String err=error.getDescription().toString();
            setResult(RESULT_CANCELED, intent);
            finish();
        }
    }
}
